package com.mai.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mai.realtime.app.BaseAppV1;
import com.mai.realtime.bean.ExamQuestionBean;
import com.mai.realtime.common.Constant;
import com.mai.realtime.util.AtguiguUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * com.mai.realtime.app.dws.DwsExamTestQuestionWindow
 * 考试题目指标统计
 */
public class DwsExamTestQuestionWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new DwsExamTestQuestionWindow().init(
                4013,
                1,
                "DwsExamTestQuestionWindow",
                Constant.TOPIC_DWD_COURSE_TEST_PAPER
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {

        // 1:封装
        SingleOutputStreamOperator<ExamQuestionBean> examQuestionStream = examQeustionToPojo(stream);
        //examQuestionStream.print();

        // 2:判断独立用户
        SingleOutputStreamOperator<ExamQuestionBean> uniqeUserStream = isUniqe(examQuestionStream);
        //uniqeUserStream.print();

        // 3：开窗聚合
        SingleOutputStreamOperator<ExamQuestionBean> examQuestionWindowStream = ExamQuestionwAggWindow(uniqeUserStream);
        //examQuestionWindowStream.print();

        // 4:写出到
        examQuestionWindowStream
                .map(bean -> JSON.toJSONString(bean))
                .print();
        //.addSink(FlinkSinkUtil.getDorisSink("gmall.dws_exam_score_count_window"));

    }

    private SingleOutputStreamOperator<ExamQuestionBean> ExamQuestionwAggWindow(SingleOutputStreamOperator<ExamQuestionBean> uniqeUserStream) {
        return uniqeUserStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<ExamQuestionBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((bean, ts) -> bean.getTs() * 1000)
                )
                .keyBy(ExamQuestionBean::getQuestionId)
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<ExamQuestionBean>() {
                            @Override
                            public ExamQuestionBean reduce(ExamQuestionBean bean1,
                                                           ExamQuestionBean bean2) throws Exception {

                                bean1.setQuestionUniqueUserCount(bean1.getQuestionUniqueUserCount() + bean2.getQuestionUniqueUserCount());
                                bean1.setCorrectQuestionCount(bean1.getCorrectQuestionCount() + bean2.getCorrectQuestionCount());
                                bean1.setCorrectQuestionUniqueUserCount(bean1.getCorrectQuestionUniqueUserCount() + bean2.getCorrectQuestionUniqueUserCount());
                                bean1.setQuestionCount(bean1.getQuestionCount() + bean2.getQuestionCount());

                                return bean1;

                            }
                        },
                        new ProcessAllWindowFunction<ExamQuestionBean, ExamQuestionBean, TimeWindow>() {
                            @Override
                            public void process(Context ctx,
                                                Iterable<ExamQuestionBean> elements,
                                                Collector<ExamQuestionBean> out) throws Exception {

                                ExamQuestionBean bean = elements.iterator().next();
                                long start = ctx.window().getStart();
                                long end = ctx.window().getEnd();

                                bean.setStt(AtguiguUtil.toDateTime(start));
                                bean.setEdt(AtguiguUtil.toDateTime(end));
                                bean.setCurDate(AtguiguUtil.toDate(end));


                                out.collect(bean);


                            }
                        }
                );
    }

    private SingleOutputStreamOperator<ExamQuestionBean> isUniqe(SingleOutputStreamOperator<ExamQuestionBean> examQuestionStream) {
        return examQuestionStream
                .keyBy(bean -> bean.getUserId() + "_" + bean.getQuestionId())
                .process(new KeyedProcessFunction<String, ExamQuestionBean, ExamQuestionBean>() {
                    private ValueState<String> todayState;
                    private ValueState<String> todayCorrectUniqeUserState;


                    @Override
                    public void open(Configuration parameters) throws Exception {
                        todayState = getRuntimeContext().getState(new ValueStateDescriptor<String>("todayState", String.class));
                        todayCorrectUniqeUserState = getRuntimeContext().getState(new ValueStateDescriptor<String>("todayUniqeUserState", String.class));
                    }

                    @Override
                    public void processElement(ExamQuestionBean value,
                                               Context ctx,
                                               Collector<ExamQuestionBean> out) throws Exception {
                        String today = todayState.value();
                        String UniqeUserState = todayCorrectUniqeUserState.value();

                        String date = AtguiguUtil.toDate(value.getTs() * 1000);
                        // 状态不相等就是今天的新用户
                        if (today == null || !today.equals(date)) {
                            System.out.println("today:" + today);
                            System.out.println("date:" + date);
                            System.out.println("value:" + value);
                            todayState.update(date);

                            value.setQuestionUniqueUserCount(1L);
                            // 多次答一道题，一次答对就算答对
                        } else {
                            System.out.println("value:" + value);

                            if (value.getCorrectQuestionCount() == 1L
                                    && value.getCorrectQuestionUniqueUserCount() == 0L
                                    && !date.equals(UniqeUserState)
                            ) {
                                value.setCorrectQuestionUniqueUserCount(1L);

                                todayCorrectUniqeUserState.update(date);

                                System.out.println("date = " + date);
                            }
                        }
                        out.collect(value);
                    }
                });
    }

    private SingleOutputStreamOperator<ExamQuestionBean> examQeustionToPojo(DataStreamSource<String> stream) {
        return stream
                .map(json -> {
                    JSONObject obj = JSON.parseObject(json);

                    String questionId = obj.getString("question_id");
                    String userId = obj.getString("user_id");
                    Long isCorrect = obj.getLong("is_correct");
                    Long ts = obj.getLong("ts");

                    return

                            new ExamQuestionBean(
                                    "", "", "",
                                    userId, questionId, 1L, isCorrect, 0L, 0L,
                                    ts
                            );


                });
    }
}
